from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks, Query
from fastapi.responses import JSONResponse, FileResponse
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.session import get_db
from app.services import analytics_service, sync_service
import logging
from typing import Optional

router = APIRouter()
logger = logging.getLogger(__name__)

@router.get("/task-performance")
async def get_task_performance(
    days: int = Query(30, description="过去多少天的数据"),
):
    """
    获取任务性能指标
    """
    try:
        metrics = await analytics_service.get_task_performance_metrics(days)
        return metrics
    except Exception as e:
        logger.error(f"获取任务性能指标失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/combined")
async def get_combined_analytics():
    """
    获取综合分析数据
    """
    try:
        analytics = await analytics_service.get_combined_analytics()
        return analytics
    except Exception as e:
        logger.error(f"获取综合分析数据失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/clickhouse-stats")
async def get_clickhouse_stats():
    """
    从 ClickHouse 获取任务统计数据
    """
    try:
        stats = await sync_service.get_task_analytics()
        return stats
    except Exception as e:
        logger.error(f"获取 ClickHouse 统计数据失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/sync")
async def trigger_sync(background_tasks: BackgroundTasks):
    """
    触发数据同步
    """
    try:
        background_tasks.add_task(sync_service.sync_tasks_to_clickhouse)
        return {"message": "数据同步任务已启动"}
    except Exception as e:
        logger.error(f"启动数据同步任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/report")
async def generate_report(
    days: int = Query(30, description="过去多少天的数据"),
    format: str = Query("json", description="报告格式: json 或 csv")
):
    """
    生成分析报告
    """
    try:
        if format.lower() not in ["json", "csv"]:
            raise HTTPException(status_code=400, detail="不支持的格式，只支持 json 或 csv")
        
        result = await analytics_service.generate_analytics_report(days, format)
        
        if format.lower() == "csv":
            return FileResponse(
                path=result,
                filename="analytics_report.xlsx",
                media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            )
        else:
            return JSONResponse(content=result)
    
    except Exception as e:
        logger.error(f"生成分析报告失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e)) 